# apps/questions/views.py
from rest_framework import viewsets, filters, status, permissions
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.shortcuts import get_object_or_404
from .models import Question
from .serializers import QuestionSerializer
from apps.core.serializers import IdListSerializer, BulkDeleteSerializer
from ..common.mixins import TenantViewSetMixin


class QuestionViewSet(TenantViewSetMixin, viewsets.ModelViewSet):
    queryset = Question.objects.select_related('creator', 'subject') \
        .prefetch_related('tags').order_by('-created_at')
    serializer_class = QuestionSerializer
    filter_backends = [
        DjangoFilterBackend,
        filters.SearchFilter,
        filters.OrderingFilter
    ]
    filterset_fields = ['question_type', 'difficulty', 'status', 'subject']
    search_fields = ['title', 'analysis', 'reference']
    ordering_fields = ['created_at', 'updated_at', 'view_count', 'difficulty']
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        qs = self.queryset
        # 管理员可看所有，普通用户只能看自己的
        if not self.request.user.is_staff:
            qs = qs.filter(creator=self.request.user)
        return qs

    def perform_create(self, serializer):
        serializer.save(creator=self.request.user)

    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])
    def increment_view(self, request, pk=None):
        """增加浏览量"""
        question = get_object_or_404(Question, pk=pk)
        question.view_count += 1
        question.save(update_fields=['view_count'])
        return Response({'view_count': question.view_count})

    @action(detail=False, methods=['post'], permission_classes=[ permissions.IsAuthenticated])
    def bulk_delete(self, request):
        """批量删除试题"""
        serializer = IdListSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        if not self.request.user.is_staff:
            deleted, _ = Question.objects.filter(
                id__in=serializer.validated_data['ids'],
                creator=request.user
            ).delete()
        else:
            deleted, _ = Question.objects.filter(
                id__in=serializer.validated_data['ids']
            ).delete()

        return Response({'deleted': deleted}, status=status.HTTP_200_OK)